package com.dian.diabetes.activity.sugar;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dian.diabetes.R;
import com.dian.diabetes.activity.BasicActivity;
import com.dian.diabetes.activity.sugar.adapter.WeekPlanAdapter;
import com.dian.diabetes.activity.sugar.model.ClockModel;
import com.dian.diabetes.activity.sugar.tool.WebChromeClientSelf;
import com.dian.diabetes.db.AlarmBo;
import com.dian.diabetes.db.UserBo;
import com.dian.diabetes.db.dao.Alarm;
import com.dian.diabetes.db.dao.Diabetes;
import com.dian.diabetes.db.dao.Plan;
import com.dian.diabetes.db.dao.User;
import com.dian.diabetes.service.AlarmService;
import com.dian.diabetes.tool.Config;
import com.dian.diabetes.tool.Preference;
import com.dian.diabetes.utils.ContantsUtil;
import com.dian.diabetes.utils.DateUtil;
import com.dian.diabetes.utils.StringUtil;
import com.dian.diabetes.widget.NGridView;
import com.dian.diabetes.widget.anotation.ViewInject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

/**
 * 控糖计划图标
 * 
 * @author longbh
 * 
 */
public class SugarChartActivity extends BasicActivity implements
		OnClickListener {

	@ViewInject(id = R.id.back_btn)
	private Button backBtn;
	@ViewInject(id = R.id.sugar_plan_one)
	private TextView sugarPan;
	@ViewInject(id = R.id.mid_value_one)
	private TextView midValue;
	@ViewInject(id = R.id.low_value_one)
	private TextView lowValue;
	@ViewInject(id = R.id.high_value_one)
	private TextView highValue;
	@ViewInject(id = R.id.webview)
	private WebView webView;
	@ViewInject(id = R.id.date1)
	private TextView datePre;
	@ViewInject(id = R.id.date2)
	private TextView dateAfter;
	@ViewInject(id = R.id.unit)
	private TextView unit;

	Handler handler = new Handler();
	List<Diabetes> data;
	EChartData edata;
	String mid = "";
	String low = "";
	String high = "";
	String type = "";
	private String weekPre = "";
	private String weekAfter = "";
	
	String[] datesPre ; //一周血糖的日期类型数组( 如: 2014-2-14(晚餐前) )
	float[] arrPre ; //一周餐前血糖值的数组
	int arrPreSize = 0;//餐前的总测试数量
	String[] datesAfter ; //一周血糖的日期数组( 如: 2014-2-14(晚餐后) )
	float[] arrAfter ; //一周餐后血糖值的数组
	int arrAfterSize = 0;//餐后的 总测试数量

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sugarchart_effect);
		init();
		initActivity();

	}

	public void init() {
		Intent intent = getIntent();
		edata =  new Gson().fromJson(intent.getStringExtra("edata"),
					EChartData.class);
		data = edata.getData();
	
		Log.e("INIT DATA : ", data.size()+"");
		type = intent.getStringExtra("type");
		mid = intent.getStringExtra("mid");
		low = intent.getStringExtra("low");
		high = intent.getStringExtra("high");
		weekPre = intent.getStringExtra("weekPre");
		weekAfter = intent.getStringExtra("weekAfter");
		Log.e("INIT MID", mid);
		Log.e("weekPre   :  ", weekPre);
		Log.e("weekAfter   :  ", weekAfter);
		
		/*
		 * 设置图标上方的 血糖偏高偏低正常的统计
		 */
		midValue.setText(mid);
		lowValue.setText(low);
		highValue.setText(high);
		datePre.setText(weekPre);
		dateAfter.setText(weekAfter);
		DataInit();
		loadFlowHtml();
		
	}
	@SuppressLint("JavascriptInterface")
	void loadFlowHtml() {
//		webView = (WebView) findViewById(R.id.webview);
		// 设置WebView属性，能够执行JavaScript脚本
		webView.getSettings().setJavaScriptEnabled(true);
		//设置可以访问文件
		webView.getSettings().setAllowFileAccess(true);
		//设置可使用cookie
		CookieManager.getInstance().setAcceptCookie(true);
		//去a input标签边框
		webView.getSettings().setNeedInitialFocus(false);
		//加载js访问控件
		webView.addJavascriptInterface(this, "SurveyUtil");
		//设置捕捉js事件
		webView.setWebChromeClient(new WebChromeClientSelf(this));
		//设置背景为透明
		webView.setBackgroundColor(getResources().getColor(android.R.color.transparent));
		webView.getSettings().setDefaultTextEncodingName("utf-8") ;
		//加载wap页面
//		String dayArrays="['2014-02-01','2014-02-02','2014-02-03','2014-02-04','2014-02-05','2014-02-06','2014-02-07','2014-02-08','2014-02-09','2014-02-10']";
		//注意格式  为[开头,]结尾,数据之间,分隔
//		String flowUseArrays="[80,20,10,75,100,200,100,800,20,59]";
//		Log.e("String URL    :   ", "?dayArrays="+Arrays.toString(dates)+"&flowUseArrays="+Arrays.toString(arr));
		String date = new String();
		String arr = new String();
		
		if(type.equals("0")){
			Log.e("String datesPre", Arrays.toString(datesPre));
			Log.e("String arrPre", Arrays.toString(arrPre));
			date = Arrays.toString(datesPre);
			arr =  Arrays.toString(arrPre);
//			webView.loadUrl("file:///android_asset/www/flow_use_now_report.html?dayArrays="+Arrays.toString(datesPre)+"&flowUseArrays="+Arrays.toString(arrPre));
		}else{
			Log.e("String datesAfter", Arrays.toString(datesAfter));
			Log.e("String arrAfter", Arrays.toString(arrAfter));
			date = Arrays.toString(datesAfter);
			arr =  Arrays.toString(arrAfter);
//				webView.loadUrl("file:///android_asset/www/flow_use_now_report.html?dayArrays="+Arrays.toString(datesAfter)+"&flowUseArrays="+Arrays.toString(arrAfter));
		}
		if(date.equals("[]")){
			webView.loadUrl("http://ydyl.dazd.cn/www/Null.html");
			datePre.setVisibility(View.INVISIBLE);
			dateAfter.setVisibility(View.INVISIBLE);
			unit.setVisibility(View.INVISIBLE);
			
		}else{
//			try {
//				date = URLEncoder.encode(date, "UTF-8");
//				arr = URLEncoder.encode(arr,"UTF-8");
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			} 
			webView.loadUrl("http://ydyl.dazd.cn/www/flow_use_now_report.html?dayArrays="+date+"&flowUseArrays="+arr);
		}
		
		Log.e("datesPre   ", Arrays.toString(datesPre));
		Log.e("arrPre   ", Arrays.toString(arrPre));
		Log.e("datesAfter   ", Arrays.toString(datesAfter));
		Log.e("arrAfter   ", Arrays.toString(arrAfter));
//		webView.loadUrl("file:///android_asset/www/flow_use_now_report.html");
//		try {
//			Thread.sleep(500);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		handler.post(new Runnable() {
//			@Override
//			public void run() {
//				String date = new String();
//				String arr = new String();
//				if(type.equals("0")){
//					date = Arrays.toString(datesPre);
//					arr =  Arrays.toString(arrPre);
//				}else{
//					date = Arrays.toString(datesAfter);
//					arr =  Arrays.toString(arrAfter);
//				}
//				Log.e("dateH  :    ", date);
//				Log.e("arrH  :    ", arr);
//				date = date.replaceAll(",", "','");//[2014-02-01','2014-02-02','2014-02-03','2014-02-04','2014-02-05]
//				date = date.replace("[", "['");
//				date = date.replace("]", "']");
//				Log.e("hahahaha", date);
//				try {
//					date = URLEncoder.encode(date,"UTF-8");
//					arr = URLEncoder.encode(arr,"UTF-8");
//				} catch (UnsupportedEncodingException e) {
//					e.printStackTrace();
//				} 
//				
//					[2014-02-01,2014-02-02,2014-02-03,2014-02-04,2014-02-05]
//					webView.loadUrl("javascript:refershView(['2014-02-01','2014-02-02','2014-02-03','2014-02-04','2014-02-05','2014-02-06','2014-02-07','2014-02-08','2014-02-09','2014-02-10'],[80,20,10,75,100,200,100,800,20,59]);");
//				webView.loadUrl("javascript:refershView(" + date + "," + arr + ");");
//				}
//		});
		
		arrPreSize = 0;
		arrAfterSize = 0;
	}
	private void DataInit(){
//		Log.e("data   :   hehe", Arrays.toString(data));
		/*
		 * 分别获取餐前和餐后的数量
		 */
		for(int i = 0, len = data.size();i<len;i++){
			if(data.get(i).getSub_type() == 0){
				arrPreSize ++ ;
			}
			if(data.get(i).getSub_type() == 1){
				arrAfterSize ++ ;
			}
		}
		
		datesPre = new String[arrPreSize];
		datesAfter = new String[arrAfterSize];
		arrPre = new float[arrPreSize];
		arrAfter = new float[arrAfterSize];
		
		int preNum = 0; //计数  餐前
		int afterNum = 0;//计数  餐后
		for(int i=0,len=data.size();i<len;i++){
			
			Diabetes diabetes = data.get(i);
			/*
			 * 餐前统计 讲时间和血糖值分别存入两个数组中
			 */
			if(diabetes.getSub_type() == 0){
				Long timeDelta = diabetes.getCreate_time();
				String date = DateUtil.parseToDate(timeDelta);
				datesPre[preNum] = date+getType(diabetes);
				arrPre[preNum] = diabetes.getValue();
				preNum ++;
			}
			/*
			 * 餐后统计 讲时间和血糖值分别存入两个数组中
			 */
			if(diabetes.getSub_type() == 1){
				Long timeDelta = diabetes.getCreate_time();
				String date = DateUtil.parseToDate(timeDelta);
				datesAfter[afterNum] = date+getType(diabetes);
				arrAfter[afterNum] = diabetes.getValue();
				afterNum ++;
			}
		}
	}

	private void initActivity() {
		sugarPan.setOnClickListener(this);
		backBtn.setOnClickListener(this);
	}

	/**
	 * 获取餐别的中文(如 : 晚餐前)
	 * 
	 * @param diabetes
	 * @return
	 */
	private String getType(Diabetes diabetes) {
		String type = ""; // 晚餐
		String subType = ""; // 前 后
		switch (diabetes.getType()) {
		case 0:
			type = "早餐";
			break;
		case 1:
			type = "中餐";
			break;
		case 2:
			type = "晚餐";
			break;
		case 3:
			type = "睡";
			break;
		}
		switch (diabetes.getSub_type()) {
		case 0:
			subType = "前";
			break;
		case 1:
			subType = "后";
			break;
		}
		return type + subType;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.back_btn:
			finish();
			break;
		case R.id.sugar_plan_one:
			context.startActivity(null, PlanActivity.class);
			break;
		}
	}

}
